<template>
	<view class="container">
		<view class="top-box" :style='{"background-image":"url("+imgUrl+")"}'>
			<view v-if="noticeText" class="top-notice">
				<uni-notice-bar :scrollable="noticeConfig.notice_scroll" single="true" :showClose="noticeConfig.notice_show_close" :speed="noticeConfig.notice_speed" :text="noticeText"></uni-notice-bar>
			</view>
			<view class="user-info-box padding-left padding-right">
				<view class="avatar flex align-center">
					<open-data type='userAvatarUrl' class="userinfo margin-right-xs" mode="cover"></open-data>
					<!-- <open-data v-if="!userInfo" class="username text-white" type="userNickName"></open-data> -->
					<view class="username text-white">{{userInfo.nickname}}</view>
				</view>
				<view class="welcome-txt text-xxl text-white margin-top">{{userInfo && userInfo.is_member ? '欢迎回来，去运动吧！' : '欢迎来到驷动健身，你还不是会员'}}</view>
				<view v-if="userInfo && userInfo.is_member" class="text-gray text-sm padding-top-xs padding-bottom-xs">你的会员有效期至<text>{{userInfo.member_expired_date}}</text>，剩余次卡次数<text>{{userInfo.member_remain_times}}次</text></view>
			</view>
			<view class="map-info">
				<view class="map padding-left padding-right">
					<map scale="17" style="width: 100%; height: 100%;" :latitude="tenant.latitude" :longitude="tenant.longitude" :markers="covers"></map>
				</view>
				<view class="rank-info-box padding-left padding-right">
					<view class="rank-info flex justify-center align-center justify-between padding" @tap="location">
						<view class="location">
							<uni-icons type="location" color="#699af8" size="20"></uni-icons>
							<text class="text-sm margin-left-xs">{{tenant.full_address}}</text>
						</view>
						<uni-icons type="arrowright" color="#699af8" size="20"></uni-icons>
					</view>
				</view>
			</view>
			<!-- <view class="sport-info">
				<view class="sport-info-box padding-left padding-right">
					<view class="summary padding radius margin-top text-white">
						<view class="title text-xl">累计运动</view>
						<view class="sport-time text-xxl margin-top-sm">尚未开始</view>
					</view>
				</view>
				<view class="rank-info-box padding-left padding-right">
					<view class="rank-info flex align-center padding">
						<text class="text-sm margin-right">当月排名</text>
						<text class="text-lg">暂无</text>
					</view>
				</view>
			</view> -->
		</view>
		<view class="list-container margin-top padding-left padding-right padding-bottom">
			<view v-for="(item, index) in memberCards" :key="index" class="primary-bg i-list-item radius margin-top flex">
				<view class="image-wrapper">
					<image class="i-image margin-top-xs" :src="item.cover_url + '?v=' + Math.random()" mode="aspectFit"></image>
				</view>
				<view class="card-info-wrapper margin-left">
					<view class="title text-white margin-top-sm">{{item.name}}</view>
					<view class="remark text-sm">{{item.remark}}</view>
					<view class="price-info margin-top-xs">
						<text class="price text-lg">¥{{item.price}}</text>
						<text class="market-price text-xs margin-left">¥{{item.market_price}}</text>
					</view>
				</view>
				<view class="btn-area flex align-center">
					<button open-type="getPhoneNumber" class="btn-buy text-white text-center text-sm" v-if="!userInfo.phone" @getphonenumber="getPhoneNumber">购买</button>
					<view v-else @tap="buy(item)" class="btn-buy text-white text-center text-sm">购买</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import util from '@/utils/util.js';
import user from '@/api/user.js';
import tenant from '@/api/tenant.js';
import memberCard from '@/api/member_card.js';
import memberCardOrder from '@/api/member_card_order.js';
import notice from '@/api/notice.js';
import uniIcons from "@/components/uni-icons/uni-icons";
import uniNoticeBar from '@/components/uni-notice-bar/uni-notice-bar.vue';

export default {
	components: {uniIcons, uniNoticeBar},
	data() {
		return {
			imgUrl: `http://7ytc-pics.speedmin.com/index_bg.jpg?q=${Math.random()}`,
			tenant: null,
			covers: [],
			userInfo: null,
			memberCards: [],
			noticeText: '',
			noticeConfig: {
				notice_scroll: true,
				notice_show_close: true,
				notice_speed: 10
			}
		}
	},
	onShow() {
		let _this = this;
		_this.getMemberCards();
		_this.initUserInfo();
		_this.getTenantInfo();
		_this.getNotices();
	},
	onPullDownRefresh() {
		let _this = this;
		_this.getMemberCards();
		_this.initUserInfo();
		_this.getTenantInfo();
		_this.getNotices();
		uni.stopPullDownRefresh();
	},
	onShareAppMessage() {
		return {
			title: '快来和我一起运动吧~',
			path: '/pages/index/index'
		}
	},
	methods: {
		initUserInfo() {
			let _this = this;
			uni.login({
			  provider: 'weixin',
			  success: async function (loginRes) {
			    let params = {code: loginRes.code};
				const res = await user.me(params);
				const userInfo = res.data.user;
				_this.userInfo = userInfo;
				uni.setStorageSync('openid', res.data.auth.openid);
				uni.setStorageSync('session_key', res.data.auth.session_key);
				uni.setStorageSync('user_info', res.data.user);
				uni.setStorageSync('token', res.data.meta.token);
				uni.setStorageSync('expires_in', res.data.meta.expires_in);
			  }
			});
		},
		async getMemberCards() {
			const res = await memberCard.list();
			this.memberCards = res.data;
		},
		async getTenantInfo() {
			const res = await tenant.info();
			this.tenant = res.data;
			this.covers.push({
				latitude: res.data.latitude,
				longitude: res.data.longitude,
				iconPath: '/static/image/icon-location.png'
			});
		},
		async getNotices() {
			const res = await notice.getAllInOne();
			this.noticeText = res.data.notice_text;
			this.noticeConfig = res.data.notice_config;
		},
		async getPhoneNumber(e) {
			const _this = this;
			if (e.detail.errMsg == "getPhoneNumber:ok") {
				const ency = e.detail.encryptedData;
				const iv = e.detail.iv;
				uni.checkSession({
					success: async function(res) {
						const session_key = uni.getStorageSync('session_key');
						const openid = uni.getStorageSync('openid');
						let params = {session_key: session_key, iv: iv, encrypted_data: ency, openid: openid};
						let response = await user.updatePhone(_this.userInfo.id, params);
						uni.showModal({
							title: '成功提醒',
							content: '授权成功，请点击购买按钮购买会员卡',
							showCancel: false,
							confirmText: '我知道了',
							success(action) {
								if (action.confirm) {
									_this.initUserInfo();
								}
							}
						});
			　　　　	},
					fail: function(res) {
						uni.login({
						  provider: 'weixin',
						  success: async function (loginRes) {
							let params = {iv: iv, encrypted_data: ency, code: loginRes.code};
							await user.phoneRegister(params);
							uni.showModal({
								title: '成功提醒',
								content: '授权成功，请点击购买按钮购买会员卡',
								showCancel: false,
								confirmText: '我知道了',
								success(action) {
									if (action.confirm) {
										_this.initUserInfo();
									}
								}
							});
						  }
						});
					}
				})
			} else {
				uni.showModal({
					title: '温馨提示',
					content: '健身房使用手机号码作为会员凭证，请授权获取手机号码以购买会员卡',
					showCancel: false,
					confirmText: '我知道了'
				});
			}
		},
		async buy(item) {
			const _this = this;
			uni.login({
			  provider: 'weixin',
			  success: async function (loginRes) {
				const res = await memberCardOrder.store({code: loginRes.code, member_card_id: item.id});
				let payParams = res.data.pay_params;
				let order = res.data.order;
				uni.requestPayment({
					provider: 'wxpay',
					timeStamp: String(payParams.timeStamp),
					nonceStr: payParams.nonceStr,
					package: payParams.package,
					signType: payParams.signType,
					paySign: payParams.paySign,
					success: function (res) {
						if (res.errMsg === 'requestPayment:ok') {
							uni.showToast({
								title: '支付成功，正在查询订单状态',
								icon: 'none'
							}, 1000);
							_this.queryMemberOrderStatus(order.id);
						}
					},
					fail: function (err) {
						uni.showToast({
							title: '支付失败',
							icon: 'none'
						}, 1000);
						console.log('fail:' + JSON.stringify(err));
					}
				});
			  }
			});
		},
		async queryMemberOrderStatus(id) {
			const res = await memberCardOrder.show(id, {type: 'pay_status'});
			if (res.data.is_paid) {
				uni.showModal({
					title: '成功提醒',
					content: '你的订单已经支付成功',
					showCancel: false,
					confirmText: '查看订单',
					success(action) {
						if (action.confirm) {
							util.toMemberCardOrder();
						}
					}
				});
			} else {
				uni.showModal({
					title: '失败提醒',
					content: '你的订单成功失败',
					showCancel: false,
					confirmText: '我知道了'
				});
			}
		},
		location() {
			const _this = this;
			let latitude = _this.tenant.latitude;
			let longitude = _this.tenant.longitude;
			let name = _this.tenant.short_name;
			let address = _this.tenant.full_address;
			uni.getLocation({
			    type: 'gcj02', //返回可以用于uni.openLocation的经纬度
			    success: function (res) {
			        uni.openLocation({
			            latitude: latitude,
			            longitude: longitude,
						name: name,
						address: address
			        });
			    }
			});
		}
	}
}
</script>
<style scoped lang="less">
	.container {
		.top-box {
			width: 100%;
			// background-image: url(http://7ytc-pics.speedmin.com/index_bg.png);
			background-repeat: no-repeat;
			background-size: 100%;
			.user-info-box {
				padding-top: 100upx;
				.avatar {
					margin-right: 20upx;
					.userinfo{
					    width:50upx;
					    height: 50upx;
					    border-radius: 50%;
					    display:flex;
					    overflow: hidden;
					}
				}
			}
			.map {
				width: 100%;
				height: 330upx;
			}
			.sport-info-box {
				.summary {
					width: 100%;
					height: 200upx;
					background: #5192f7;
				}
			}
			.rank-info-box {
				.rank-info {
					width: 100%;
					height: 100upx;
					background-image: linear-gradient(90deg, #1d325e 50%, #1e3565 50%);
					background-size: 40upx 100%;
					color: #699af8;
				}
			}
		}
		.list-container {
			.i-list-item {
				height: 200upx;
				.image-wrapper {
					height: 100%;
					.i-image {
						width: 160upx;
						height: 180upx;
					}
				}
				.card-info-wrapper {
					width: 300upx;
					.remark {
						color: #939496;
					}
					.price-info {
						.price {
							color: #f6ca44;
						}
						.market-price {
							color: #939496;
							text-decoration:line-through; 
						}
					}
				}
				.btn-area {
					margin-left: 60upx;
					.btn-buy {
						width: 120upx;
						height: 44upx;
						line-height: 44upx;
						border-radius: 4upx;
						background: #485575;
						border: none;
					}
				}
			}
		}
	}
</style>